
package suncertify.db;

//~--- JDK imports ------------------------------------------------------------

import java.util.TreeMap;

/**
 *
 * @author jshah
 * Creates a <code>TreeMap</code> of LockObjects corresponding to each record, populates the ArrayList of locks with
 * key Code '-1' thats the sign of unlocked Record.
 */
public class LockRegister {
    /**
     * register      Collection of all the lock objects
     */
    TreeMap<Integer, Lock> register = new TreeMap<Integer, Lock>();
    /**
     * noOfRecords   The total number of records in the DB
     */
    int noOfRecords;

    /**
     * populate a Collection with size equal to total no of REcords
     * @param noOfRecords           The total number of records in the DB
     */
    private LockRegister(int noOfRecords) {
        this.noOfRecords = noOfRecords;

        for (int i = 0; i < this.noOfRecords; i++) {
            register.put(i, new Lock());
        }
    }

    /**
     * Factory method to obtain a new lockRegister
     * @param noOfRecords       The total of Records which determines the Size of Register
     * @return                  LockRegister which contains a corresponding Lock object for all records
     */
    static LockRegister LockRegisterGetNewInstance(int noOfRecords) {
        return new LockRegister(noOfRecords);
    }

    /**
     * If a new record is created add a Lock Object for that Record the Register
     * @param RecNo         The Record Index of new Record that is created
     */
    void addLockToRegister(int RecNo) {
        this.register.put(RecNo, new Lock());
    }

    /**
     * Defines a Lock for each record
     * @param keyCode        contains the keyCode for that Lock used to unLock
     * @param boolean        returns True if object is currently locked else False
     */
    class Lock {
        private long    keyCode = -1; //default keycode shows that keycode has not been setS
        private boolean locked  = false;

        public boolean isLocked() {
            return locked;
        }

        public void setLocked(boolean locked) {
            this.locked = locked;
        }

        public long getKeyCode() {
            return this.keyCode;
        }

        public void setKeyCode(long keyCode) {
            this.keyCode = keyCode;
        }
    }
}

